package com.init.controller;

import com.init.common.BaseResponse;
import com.init.common.ErrorCode;
import com.init.common.ResultUtils;
import com.init.exception.BusinessException;
import com.init.model.entity.Admin;
import com.init.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 管理员接口
 * @author Atanycosts
 * @date 2025/1/4
 */
@RestController
@Slf4j
@RequestMapping("/admin")
public class AdminController {


    @Resource
    private AdminService adminService;


    /**
     * 根据ID详细查询
     */
    @GetMapping("/{adminId}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('BOSS')") //用户权限
    public BaseResponse<Admin> info(@PathVariable("adminId") Integer adminId) {
        // 已排查
        Admin admin = adminService.getById(adminId);

        if (admin == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "请求数据为空");
        }
        return ResultUtils.success(admin);
    }

    /**
     * 新增管理员,BOSS可以直接添加管理员，在不方便暴露管理员注册接口的情况下
     */
    @PostMapping("/save")
    @PreAuthorize("hasRole('BOSS')") //用户权限
    public BaseResponse<String> save(@RequestBody Admin admin) {
        // 已排查

        boolean save = adminService.save(admin);

        if (save) {
            return ResultUtils.success("新增成功");
        }
        throw new BusinessException(ErrorCode.OPERATION_ERROR, "新增失败");
    }

    /**
     * 修改
     */
    @PatchMapping("/update")
    @PreAuthorize("hasRole('ADMIN') or hasRole('BOSS')") //用户权限
    @Transactional
    public BaseResponse<String> update(@RequestBody Admin admin) {
        // 已排查
        boolean b = adminService.updateById(admin);

        if (b) {
            return ResultUtils.success("修改成功");
        }
        throw new BusinessException(ErrorCode.OPERATION_ERROR, "修改失败");
    }
}
